package com.thymeleaf_study.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

public class CorsFilterConfig {
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter(){
        FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean=new FilterRegistrationBean<>();
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration=new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");//允许的请求头
//        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOriginPattern("*");//允许的origin域名
        corsConfiguration.setAllowCredentials(true); //是否允许发cookie
        corsConfiguration.setMaxAge(3600L);//从预检请求得到相应的最大时间，默认30分钟
        corsConfiguration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT")); //允许的请求方法
        source.registerCorsConfiguration("/**",corsConfiguration);//指定可以跨域的路径
        corsFilterFilterRegistrationBean.setFilter(new CorsFilter((CorsConfigurationSource) source));
        corsFilterFilterRegistrationBean.setOrder(-1);
        return corsFilterFilterRegistrationBean;
    }
}
